package com.seele.tigerwallet.ui.activtiy;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.api.APIObjectCallBack;
import com.seele.tigerwallet.model.AssetsModel;
import com.seele.tigerwallet.model.TranscationModel;
import com.seele.tigerwallet.model.TsModel;
import com.seele.tigerwallet.model.TsStaus;
import com.seele.tigerwallet.model.UserInfo;
import com.seele.tigerwallet.ui.adapter.TokenIntercourseAdapter;
import com.seele.tigerwallet.ui.base.ToolbarBaseActivity;
import com.seele.tigerwallet.ui.event.ExchangeEvent;
import com.seele.tigerwallet.ui.manager.DaoManager;
import com.seele.tigerwallet.ui.manager.GlideManager;
import com.seele.tigerwallet.ui.utils.DataUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;

/**
 * Description:交易界面
 * Data: 2018/6/9 17:30
 * author:
 */
public class TokenIntercourseActivity extends ToolbarBaseActivity implements View.OnClickListener {

    private TextView mTransferTv;
    private TextView mReceivablesTv;
    private RecyclerView mRecyclerView;
    private TextView mTokenValueTextView;//持有金额
    private TextView mTokenRmbTextView; //人民币或者美金图标
    private TextView mTokenRmbCount; //人民币或者美金金额
    private TextView mTokenSignTextView;//;
    private LinearLayout mNoRecordLayout;
    private TokenIntercourseAdapter mTokenIntercourseAdapter;
    private static final String TAG = "IntercourseActivity";
    private AssetsModel mAssetsModel;
    public static final int REQUEST_CODE = 1;
    private TranscationModel mTranscationModel;
    List<TsModel> mTsModelList = new ArrayList<TsModel>();
    private UpdateTimer mUpdateTimer;

    @Override
    public int getContainerViewId() {
        return R.layout.activity_intercourse_token;
    }

    @Override
    protected void initView() {
        try{
            Bundle bundle = getIntent().getExtras();
            mAssetsModel = (AssetsModel) bundle.getSerializable(TokenIntercourseActivity.class.getSimpleName());
            mTransferTv = $f(R.id.transfer_token_tv);
            mReceivablesTv = $f(R.id.receivables_token_tv);
            mTokenValueTextView = $f(R.id.token_value_tv);
            mTokenRmbTextView = $f(R.id.token_rmb_tv);
            mTokenSignTextView = $f(R.id.token_sign_tv);
            LinearLayout layoutTransfer = $f(R.id.layout_transfer_token_tv);
            LinearLayout layoutReceipt = $f(R.id.layout_receivables_token_tv);
            mNoRecordLayout = $f(R.id.layout_norecord);
            layoutTransfer.setOnClickListener(this);
            layoutReceipt.setOnClickListener(this);
            mTokenRmbCount = $f(R.id.token_rmb_count);

            setBackgroundColor(R.color.color_FFFFFF);
            setTitle(mAssetsModel.symbol);
            setValue();
            mRecyclerView = $f(R.id.recyclerView);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            ImageView imageView =  $f(R.id.token_icon_img);
            GlideManager.loadUrl(this, mAssetsModel.id + "", imageView);
            mUpdateTimer = new UpdateTimer();
            mTokenIntercourseAdapter = new TokenIntercourseAdapter(R.layout.item_token_intercourse);
            mRecyclerView.setAdapter(mTokenIntercourseAdapter);
            mTokenIntercourseAdapter.setNewData(mTsModelList);
            mTokenIntercourseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    Bundle bundle = new Bundle();
                    TsModel tsModel = mTsModelList.get(position);
                    tsModel.symbol = mAssetsModel.symbol;
                    bundle.putSerializable(RecordaActivity.class.getSimpleName(), mTsModelList.get(position));
                    startActivity(RecordaActivity.class, bundle);
                }
            });
            Loadlocal();
        }catch (Exception e){
            Log.e(TAG, "initView failed:" + e.getMessage());
        }

    }

    private void setAsset(AssetsModel assetsModel) {
        if (assetsModel == null) {
            Log.e(TAG, "setAsset assetsModel is null.");
            return;
        }
        try {
            if (DataUtils.isCNY()) {
                mTokenRmbTextView.setText(getResources().getString(R.string.cny));
            } else {
                mTokenRmbTextView.setText(getResources().getString(R.string.usdt));
            }
            String value = "";
            if (!TextUtils.isEmpty(assetsModel.balance) && assetsModel.balance.length() > 4) {
                value = DataUtils.getFourDecimal(assetsModel.balance);
            } else {
                value = "0.0000";
            }
            mTokenValueTextView.setText(value);//设置余额
            String total = DataUtils.getSingleTokenValue(mAssetsModel.price, mAssetsModel.balance);
            mTokenRmbCount.setText(total);
        } catch (Exception e) {
            Log.e(TAG, "setAsset exp:" + e.getMessage());
        }

    }

    private void setValue() {
        try {
            String value = "";
            if (!TextUtils.isEmpty(mAssetsModel.balance) && mAssetsModel.balance.length() > 4) {
                value = DataUtils.getFourDecimal(mAssetsModel.balance);
            }else {
                value = "0.0000";
            }
            mTokenValueTextView.setText(value);//设置余额
            if (DataUtils.isCNY()) {
                mTokenRmbTextView.setText(getResources().getString(R.string.cny));
            } else {
                mTokenRmbTextView.setText(getResources().getString(R.string.usdt));
            }

            String total = DataUtils.getSingleTokenValue(mAssetsModel.price, mAssetsModel.balance);
            mTokenRmbCount.setText(total);
        } catch (Exception e) {
            Log.e(TAG, "setValue exp:" + e.getMessage());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (null != mUpdateTimer) {
            mUpdateTimer.startTimer();
        }

    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().post(new  ExchangeEvent());
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != mUpdateTimer) {
            mUpdateTimer.stopTimer();
        }
    }

    @Override
    public void onClick(View view) {
        try {
            Bundle bundle = new Bundle();
            switch (view.getId()) {
                case R.id.layout_transfer_token_tv://转账跳转
                    bundle.putSerializable(TransferTokenActivity.class.getSimpleName(), mAssetsModel);
                    Intent intent = new Intent(TokenIntercourseActivity.this, TransferTokenActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, REQUEST_CODE);
                    break;

                case R.id.layout_receivables_token_tv://收款跳转
                    bundle.putSerializable(ReceiptActivity.class.getSimpleName(), mAssetsModel);
                    startActivity(ReceiptActivity.class, bundle);
                    break;
            }
        }catch (Exception e) {
            Log.e(TAG, "onClick failed:" + e.getMessage());
        }
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == RESULT_OK) {
                switch (requestCode) {
                    case REQUEST_CODE:
                        mTranscationModel = (TranscationModel) data.getExtras().get(TransferTokenActivity.class.getSimpleName());
                        break;
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {
            Log.e(TAG, "onActivityResult failed:" + e.getMessage());
        }

    }


    /**
     * 查询交易记录
     */
    private void queryTsInfo() {
        String address = UserInfo.get().address;
        Log.i(TAG, "from address:" + address);
        APIModule.getApi()
                .querytTsInfo(-1, mAssetsModel.id, 50, address)
                .enqueue(new APIListCallBack<TsModel>() {
                    @Override
                    protected void onResponse(List<TsModel> response) {
                        Log.i(TAG, "querytTsInfo onResponse");
                        mTsModelList = response;
                        setNewData();
                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        Log.i(TAG, "querytTsInfo onResponseError");
                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        Log.i(TAG, "querytTsInfo onFailureError");
                    }
                });

    }


    /**
     * 查询当前币种资产余额
     */
    private void querySymbol() {
        String address = UserInfo.get().address;
        APIModule.
                getApi().
                querySymbol(address, mAssetsModel.id+"").
                enqueue(new APIListCallBack<AssetsModel>() {
                    @Override
                    protected void onResponseError(APIException e) {
                        Log.e(TAG, "querySymbol onResponseError");
                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        Log.e(TAG, "querySymbol onFailureError");
                    }

                    @Override
                    protected void onResponse(List<AssetsModel> response) {
                        AssetsModel model = response.get(0);
                        mAssetsModel.id = model.id;
                        //mAssetsModel.symbol = model.symbol;
                        mAssetsModel.balance = model.balance;
                        mAssetsModel.price = model.price;
                        setAsset(mAssetsModel);
                    }
                });
    }



    /**
     * 查询交易状态
     */
    private void queryTsStaus(int tsid, int symbolid) {
        String fromAddress = UserInfo.get().address;
        Log.i(TAG, "from address:" + fromAddress);
        final int id = tsid;
        APIModule.getApi()
                .queryTsStaus(tsid, symbolid)
                .enqueue(new APIObjectCallBack<TsStaus>() {
                    @Override
                    protected void onResponse(TsStaus response) {
                        Log.i(TAG, "onResponse:" + "tsstatus:" + response.tsstatus + ",tsacknum" + response.tsacknum + ",tsid:" + id);
                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        Log.i(TAG, "onResponseError");
                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        Log.i(TAG, "onFailureError");
                    }
                });

    }

    private void setNewData() {
        try {
            mTokenIntercourseAdapter.removeAllFooterView();
            if (mTsModelList != null && mTsModelList.size() >=1) {
                mNoRecordLayout.setVisibility(View.GONE);
                mRecyclerView.setVisibility(View.VISIBLE);
            }
            mTokenIntercourseAdapter.setNewData(mTsModelList);
            mTokenIntercourseAdapter.notifyDataSetChanged();
            saveTsModels();
        } catch (Exception e) {
            Log.e(TAG, "setNewData failed:" + e.getMessage());
        }
    }

    private void saveTsModels() {
        if (null != mTsModelList && mTsModelList.size() > 0) {
            for (int i = 0; i < mTsModelList.size(); i++) {
                TsModel tsModel = mTsModelList.get(mTsModelList.size() - i - 1);
                tsModel.symbolid = mAssetsModel.id;
                tsModel.symbol = mAssetsModel.symbol;
                DaoManager.saveOrUpdate(tsModel);
            }
        }
    }


    class UpdateTimer {
        private Timer mTimer;
        private TimerTask mTimerTask;

        public UpdateTimer() {
        }

        public void startTimer() {
            if (mTimer == null) {
                mTimer = new Timer();
            }
            if (mTimerTask == null) {
                mTimerTask = new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            queryTsInfo();
                            querySymbol();
                        } catch (Exception e) {
                            Log.e(TAG, "timer run failed:" + e.getMessage());
                        }
                    }
                };
            }
            if (mTimerTask != null)
                mTimer.schedule(mTimerTask, 0, 10 * 1000);
        }

        public void stopTimer() {
            if (mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
            if (mTimerTask != null) {
                mTimerTask.cancel();
                mTimerTask = null;
            }
        }
    }


    private void Loadlocal() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mTsModelList = DaoManager.getTsModelsDao().queryBuilder().orderBy("tsid", false).where().eq("symbolid", mAssetsModel.id).query();
                    if (null != mTsModelList && mTsModelList.size() > 0) {
                        setNewData();
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Loadlocal failed:" + e.getMessage());
                }
            }
        }).start();
    }



}
